﻿using System;
using System.Web.UI.WebControls;
using System.Web;
using System.IO;
using System.Drawing.Imaging;
using System.Web.UI;
using System.Drawing;

namespace LG.Web
{
    public static class FileHelper
    {
        /// <summary>
        /// 得到文件名
        /// </summary>
        /// <param name="path">文件</param>
        /// <returns></returns>
        public static string GetFileName(string path)
        {
            //return Path.GetFileName(path);
            string[] parts=path.Split ('\\','/');
            if (parts.Length == 0)
                return string.Empty;
            else
                return parts[parts.Length - 1];
        }

        public static string GetExt(string filename)
        {
            string[] parts = filename.Split('.');
            if (parts.Length == 0)
                return string.Empty;
            string ext = "." + parts[parts.Length - 1];
            return ext;
        }
        
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="localPath"></param>
        public static void DeleteFile(string localPath)
        {
            if (File.Exists(localPath))
            {
                File.Delete(localPath);
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fu">FileUpload上传控件</param>
        /// <param name="servFolderPath">服务器地址</param>
        /// <param name="checkFile">是否验证文件的存在</param>
        /// <param name="inName">输入文件名，如果为空，文件名系统生成,如果不为空，文件名即inname</param>
        /// <param name="outName">上传后的文件名</param>
        /// <returns></returns>
        public static bool UploadFile(FileUpload fu, string servFolderPath, bool checkFile, string inName, out string outName)
        {
            if (fu.HasFile)
            {
                if (string.IsNullOrEmpty(inName))
                {
                    outName = Guid.NewGuid().ToString().Replace("-", "");
                }
                else
                {
                    outName =inName .Split ('.')[0];
                }
                string[] parts = fu.FileName.Split('.');
                outName = outName + "." + parts[parts.Length - 1];
            }
            else
            {
                outName = inName;
                if (checkFile)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            string path= HttpContext.Current.Server.MapPath(servFolderPath);
            if(!Directory.Exists (path ))
            {
                Directory .CreateDirectory (path);
            }
            try
            {
                fu.PostedFile.SaveAs (path +outName );
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
